<template>
  <div class="bigbox">
    <!-- 表头盒子 -->
    <div class="leftbox">
      <!-- 树节点过滤 -->
      <div class="tree-top">
        <el-select
          v-model="selectValue"
          placeholder="请选择"
          @change="changeSelect"
        >
          <el-option
            v-for="item in selectList"
            :key="item.value"
            :label="item.text"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <div class="tree-add" @click="openTreeModle">
          <i class="el-icon-plus"></i>
        </div>
      </div>
      <!-- 树组件 -->
      <div style="margin-top: 15px" v-if="selectValue">
        <el-tree
          ref="tree"
          :props="props"
          :data="list"
          v-loading="treeLoading"
          :highlight-current="true"
          @node-click="handleNodeClick"
          :default-checked-keys="[0]"
          :load="loadNode"
          node-key="nodeId"
          lazy
        >
          <span slot-scope="{ node }" class="slot-t-node">
            <template>
              <div style="display: flex; align-items: center">
                <img
                  v-if="node.data.imageBase64"
                  style="margin-right: 5px"
                  :src="'data:image/png;base64,' + node.data.imageBase64"
                />
                <span :style="{ 'font-size': '14px' }">{{
                  node.data.nodeName
                }}</span>
              </div>
            </template>
          </span>
        </el-tree>
      </div>
    </div>
    <!-- 盒子主体 -->
    <div class="mainbox">
      <div class="top">
        <div class="search">
          <el-input
            placeholder="请输入关键字搜索"
            prefix-icon="el-icon-search"
            v-model="inputValue"
          >
          </el-input>
        </div>
        <div class="towBtn">
          <button @click="chongzhi" class="button">重置</button>
          <button @click="chaxun" class="button chaxun">查询</button>
        </div>
      </div>
      <div class="bodybox">
        <!-- 新增按钮 -->
        <!-- 循环图片盒子 -->
        <div class="table">
          <div class="titlebox">
            <div class="text"></div>
            <div
              class="right"
              :style="{ alignItems: 'center', lineHeight: '32.5px' }"
            >
            <button
                type="primary"
                size="small"
                v-if="node?.level==1"
                style="margin-right: 10px;"
                class="bewdao daochu"
                @click="menuMaintain({nodeId})"
              >
                根节点菜单维护
              </button>
              <button
                type="primary"
                size="small"
                v-if="nodeId"
                class="bewdao daochu"
                @click="addNode"
              >
                <i style="margin-left: 0px" class="el-icon-plus"></i>新增
              </button>
              <el-tooltip
                class="item"
                effect="dark"
                content="刷新"
                placement="top"
              >
                <span
                  @click="shuaxin"
                  :style="{ cursor: 'pointer', fontSize: '20px' }"
                  ><i class="el-icon-refresh-right"></i
                ></span>
              </el-tooltip>
              <el-dropdown trigger="click" @command="command">
                <span class="el-dropdown-link">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="密度"
                    placement="top"
                  >
                    <span :style="{ cursor: 'pointer', fontSize: '20px' }"
                      ><i class="el-icon-d-caret"></i
                    ></span>
                  </el-tooltip>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item class="dropdown-list" command="默认"
                    >默认</el-dropdown-item
                  >
                  <el-dropdown-item class="dropdown-list" command="中等"
                    >中等</el-dropdown-item
                  >
                  <el-dropdown-item class="dropdown-list" command="紧凑"
                    >紧凑</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            border
            height="77vh"
            id="exportTabyong"
            ref="table"
            :size="iissize"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center',
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <!-- <el-table-column
              align="center"
              type="index"
              width="50"
              label="序号"
            >
            </el-table-column> -->
            <el-table-column align="left" prop="nodeName" label="节点名称">
            </el-table-column>
            <el-table-column
              align="left"
              prop="nodeClassName"
              label="关联类名称"
            >
            </el-table-column>
            <el-table-column align="left" prop="nodeType" label="节点类型">
              <template slot-scope="scope">
                <span>{{
                  scope.row.nodeType === 0 ? "根节点" : "类节点"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column width="250px" align="center" label="操作">
              <template slot-scope="scope">
                <div class="table-cz">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="编辑"
                    placement="top"
                  >
                    <i
                      style="
                        font-size: 14px;
                        color: rgb(64, 149, 229);
                        cursor: pointer;
                      "
                      class="el-icon-edit"
                      @click="edit(scope.row)"
                    ></i
                  ></el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除"
                    placement="top"
                  >
                    <i
                      style="font-size: 14px; color: red; cursor: pointer"
                      class="el-icon-delete"
                      @click="del(scope.row)"
                    ></i></el-tooltip
                  ><el-tooltip
                    class="item"
                    effect="dark"
                    content="上移"
                    placement="top"
                  >
                    <i
                      style="
                        font-size: 14px;
                        color: rgb(64, 149, 229);
                        cursor: pointer;
                      "
                      class="el-icon-upload2"
                      @click="move('up', scope.row)"
                    ></i>
                  </el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="下移"
                    placement="top"
                  >
                    <i
                      style="
                        font-size: 14px;
                        color: rgb(64, 149, 229);
                        cursor: pointer;
                      "
                      class="el-icon-download"
                      @click="move('down', scope.row)"
                    ></i
                  ></el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="节点菜单维护"
                    placement="top"
                  >
                    <img
                      style="width: 14px; height: 14px; cursor: pointer"
                      src="../../../assets/image/list.png"
                      @click="menuMaintain(scope.row)"
                  /></el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-dialog
          :show-close="true"
          :visible.sync="TreeModelVisible"
          width="1000px"
          top="5vh"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :before-close="diaClose"
          append-to-body
          :center="true"
        >
          <ModelTreeTable v-if="TreeModelVisible"></ModelTreeTable>
          <div style="height: 20px"></div>
        </el-dialog>
        <el-dialog
          :show-close="true"
          :visible.sync="TreeNodeVisible"
          v-if="TreeNodeVisible"
          width="1000px"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :before-close="diaClose"
          append-to-body
          :center="true"
        >
          <div class="treeNode-top">
            <div class="left">
              <div class="search">
                <el-input
                  placeholder="请输入关键字搜索"
                  prefix-icon="el-icon-search"
                  v-model="filterText"
                >
                </el-input>
              </div>
            </div>
            <div class="towBtn">
              <button @click="chongzhi2" class="button">重置</button>
              <button @click="chaxun2" class="button chaxun">查询</button>
            </div>
          </div>
          <TableUse
            v-loading="loading2"
            border
            :data="addTreeNodeList"
            max-height="400px"
            ref="table"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center',
            }"
            name="relationClassId"
            :tableConfig="tableConfig"
            @selection-change="chooseList"
          >
          </TableUse>
          <div style="margin-top: 20px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="diaClose">取 消</el-button>
              <el-button type="primary" @click="tableSubmit">确 定</el-button>
            </span>
          </div>
        </el-dialog>
        <el-dialog
          :show-close="true"
          :visible.sync="nodeVisible"
          v-if="nodeVisible"
          width="500px"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :before-close="diaClose"
          append-to-body
          :center="true"
        >
          <el-form
            ref="nodeForm"
            :rules="nodeRules"
            :model="nodeform"
            label-width="110px"
          >
            <el-form-item label="节点名称" prop="nodeName">
              <el-input v-model="nodeform.nodeName"></el-input>
            </el-form-item>
          </el-form>
          <div style="margin-top: 20px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="diaClose">取 消</el-button>
              <el-button type="primary" @click="nodeSubmit">确 定</el-button>
            </span>
          </div>
        </el-dialog>
        <el-dialog
          :show-close="true"
          :visible.sync="menuVisible"
          v-if="menuVisible"
          width="1000px"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :before-close="diaClose"
          append-to-body
          :center="true"
        >
          <MenuMaintain :data="menuData"></MenuMaintain>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  addTreeNodeApi,
  delTreeNodeApi,
  downTreeNodeApi,
  editTreeNodeApi,
  getAddTreeNodeListApi,
  getModelTreeSelectApi,
  getTreeChildListApi,
  getTreeNodeDataApi,
  getTreeRootListApi,
  upTreeNodeApi
} from '@/api/Model-all/Model-tree'
import TableUse from '../components/TableUse.vue'
import ModelTreeTable from './components/ModelTreeTable.vue'
import MenuMaintain from './components/MenuMaintain.vue'
export default {
  name: 'ModelTreeIndex',
  components: {
    ModelTreeTable,
    TableUse,
    MenuMaintain
  },
  data () {
    return {
      selectList: [],
      list: [],
      classId: '',
      selectValue: '',
      treeLoading: false,
      inputValue: '',
      filterText: '',
      nodeId: '',
      node: null,
      addTreeNodeList: [],
      tableData: [],
      loading: false,
      loading2: false,
      iissize: 'medium',
      nodeform: {},
      tableConfig: [
        {
          align: 'left',
          prop: 'relationClassCode',
          label: '类编码'
        },
        {
          align: 'left',
          prop: 'relationClassName',
          label: '类名称'
        }
      ],
      nodeRules: {
        nodeName: [
          { required: true, message: '请输入节点名称', trigger: 'blur' }
        ]
      },
      rules1: {
        classCode: [
          { required: true, message: '请输入类编码', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '请输入类名称', trigger: 'blur' }
        ]
      },
      deflist: [],
      props: {
        label: 'nodeName'
      },
      menuData: {},
      TreeNodeVisible: false,
      TreeModelVisible: false,
      menuVisible: false,
      nodeVisible: false,
      isedit: 'add'
    }
  },
  created () {
    this.initTree()
  },
  mounted () {},
  methods: {
    // 页面初始化
    async initTree () {
      await this.getModelTreeSelect()
      await this.getTreeRootList(this.selectValue)
      this.refreshNode(this.list[0].nodeId)
      this.getTreeChildList(this.list[0].nodeId)
      this.nodeId = this.list[0].nodeId
    },
    // 查询模型层次树下拉框列表
    async getModelTreeSelect () {
      const res = await getModelTreeSelectApi()
      console.log('下拉框', res)
      this.selectList = res.data.list
      this.selectValue = res.data.list[0].value
    },
    // 树根节点数据
    async getTreeRootList (id) {
      this.treeLoading = true
      const res = await getTreeRootListApi(id)
      this.list = res.data.list
      this.treeLoading = false
      console.log('树根节点', this.list)
    },
    // 树子节点数据
    async getTreeChildList (nodeId) {
      this.loading = true
      const res = await getTreeChildListApi(nodeId)
      this.deflist = res.data.list
      this.tableData = res?.data.list
      this.loading = false
    },
    // 模型层次树下拉框选择
    async changeSelect (val) {
      console.log(val)
      await this.getTreeRootList(val)
      this.refreshNode(this.list[0].nodeId)
      this.getTreeChildList(this.list[0].nodeId)
    },
    // 打开层次树维护
    async openTreeModle () {
      this.TreeModelVisible = true
    },
    // 查询可新增类关系列表
    async getAddTreeNodeList () {
      this.loading2 = true
      const res = await getAddTreeNodeListApi(this.nodeId)
      this.deflist2 = res.data.list
      this.addTreeNodeList = res.data.list
      this.loading2 = false
    },
    addNode () {
      this.getAddTreeNodeList()
      this.TreeNodeVisible = true
    },
    chooseList (arr) {
      this.classId = arr
      console.log(this.classId)
    },
    // 节点菜单维护
    async menuMaintain (item) {
      console.log(item)
      this.menuData = item
      this.menuVisible = true
    },
    diaClose () {
      this.TreeModelVisible = false
      this.TreeNodeVisible = false
      this.nodeVisible = false
      this.menuVisible = false
      this.nodeform = {}
    },
    async shuaxin () {
      await this.getTreeChildList(this.nodeId)
      this.chaxun()
      this.$message({
        type: 'success',
        message: '列表刷新成功',
        duration: 2000
      })
    },
    // 关键词查找
    async chaxun () {
      const list = [...this.deflist]
      if (this.inputValue) {
        console.log(list)
        console.log(this.tableData)
        this.tableData = list.filter((item) =>
          Object.values(item).includes(this.inputValue)
        )
      } else {
        this.tableData = [...list]
      }
    },
    // 关键词查找
    async chaxun2 () {
      this.getAddTreeNodeList()
      const list = [...this.deflist2]
      const filteredData = list.filter((item) => {
        return Object.values(item).some((value) => {
          if (typeof value === 'string' && value.includes(this.filterText)) {
            return true
          }
          return false
        })
      })
      if (this.filterText) {
        this.addTreeNodeList = [...filteredData]
      } else {
        this.addTreeNodeList = [...this.deflist2]
      }
    },
    chongzhi () {
      this.inputValue = ''
      this.chaxun()
    },
    chongzhi2 () {
      this.filterText = ''
      this.chaxun2()
    },
    command (val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    refreshNode (key) {
      console.log('key', key)
      // 获取当前节点，key可以在@node-click和:load绑定函数的回调参数node用变量存储后有需要刷新的地方取node.key
      const node = this.$refs.tree.getNode(key)
      this.node = node
      console.log('node', node)
      //  设置未进行懒加载状态
      node.loaded = false
      // 重新展开节点就会间接重新触发load达到刷新效果
      this.$nextTick(() => {
        node.expand()
      })
    },
    // 树节点点击
    async handleNodeClick (val, node) {
      console.log('1', val)
      this.node = node
      this.nodeId = val.nodeId
      console.log('node', this.node)
      this.getTreeChildList(this.nodeId)
    },
    // 树组件懒加载
    async loadNode (node, resolve) {
      // if (node.level === 0) {
      //   // 初始的级数（最顶层）
      //   const res = await getTreeRootListApi(this.selectValue)
      //   return resolve(res.data.list) // 最顶层数据渲染为region
      // }
      // if (node.level === 1) {
      //   const res = await getRootDomainListApi()
      //   return resolve(res?.data.list)
      // } else
      if (node.level >= 1) {
        const res = await getTreeChildListApi(node.data.nodeId)
        return resolve(res?.data.list)
      } else {
        return resolve([])
      }
    },
    // 树节点新增
    async tableSubmit () {
      const res = await addTreeNodeApi({
        classId: this.classId,
        parentNodeId: this.nodeId
      })
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: res.message,
          duration: 2000
        })
        this.chaxun2()
        this.getTreeChildList(this.nodeId)
        this.refreshNode(this.node.key)
      } else {
        this.$message({
          type: 'error',
          message: res.message,
          duration: 2000
        })
      }
    },
    // 移动
    async move (type, item) {
      this.$confirm('此操作将移动模型类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res =
            type === 'up'
              ? await upTreeNodeApi(item.nodeId)
              : await downTreeNodeApi(item.nodeId)
          console.log(res)
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: res.message,
              duration: 2000
            })
            this.updataIndex()
          } else {
            this.$message({
              type: 'error',
              message: res.message,
              duration: 2000
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消移动',
            duration: 2000
          })
        })
    },
    // 编辑
    async edit (item) {
      this.isedit = 'edit'
      const res = await getTreeNodeDataApi(item.nodeId)
      // console.log(res)
      const data = res.data.entity
      this.$set(this.nodeform, 'nodeId', data.nodeId)
      this.$set(this.nodeform, 'nodeName', data.nodeName)
      console.log(item)
      this.nodeVisible = true
    },
    updataIndex () {
      this.getTreeChildList(this.nodeId)
      this.refreshNode(this.node.key)
    },
    async nodeSubmit () {
      const res = await editTreeNodeApi(this.nodeform)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: res.message,
          duration: 2000
        })
        this.updataIndex()
        this.diaClose()
      } else {
        this.$message({
          type: 'error',
          message: res.message,
          duration: 2000
        })
      }
    },
    // 删除节点
    async del (item) {
      this.$confirm('此操作将删除该层次树节点,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await delTreeNodeApi(item.nodeId)
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: res.message,
                duration: 2000
              })
              this.updataIndex()
            } else {
              this.$message({
                type: 'error',
                message: res.message,
                duration: 2000
              })
            }
          } catch (e) {
            console.log(e)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            duration: 2000
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.treeNode-top {
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 80px;
  background-color: #fff;
  border-bottom: 1px solid #f1f1f1;
  margin-bottom: 10px;
  align-items: center;
  .left {
    display: flex;
    align-items: center;
    .group-select {
      width: 200px;
      margin-right: 10px;
    }
    .group-add {
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      border: 1px solid #dcdfe6;
      border-radius: 5px;
      width: 25px;
      height: 25px;
      margin-right: 20px;
    }
    .search {
      display: flex;
      align-items: center;
      width: 200px;
    }
  }
}
.table-cz {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
.bigbox {
  background-color: #f1f1f1;
  min-height: 100%;
  padding: 9px;
  display: flex;
  .leftbox {
    width: 300px;
    background-color: #fff;
    padding: 20px;
    .tree-top {
      display: flex;
      align-items: center;
      .tree-add {
        display: flex;
        margin-left: 10px;
        align-items: center;
        text-align: center;
        cursor: pointer;
      }
    }
  }
  .mainbox {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    .top {
      padding: 0 40px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      min-height: 80px;
      background-color: #fff;
      border-bottom: 1px solid #f1f1f1;
      margin-bottom: 10px;
      align-items: center;
      .search {
        display: flex;
        align-items: center;
        width: 400px;
      }
    }
    .bodybox {
      flex: 1;
      position: relative;
      background-color: #fff;
      padding: 20px;
      padding-bottom: 30px;
      min-height: 87.6vh;
      .table {
        .titlebox {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          .text {
            font-size: 16px;
          }
          .right {
            align-items: center;
            i {
              margin-left: 10px;
            }
            .bewdao {
              padding: 5px 10px;
              height: 32px;
            }
            .daochu {
              background-color: #1890ff;
              color: #fff;
              border: none;
              border-radius: 3px;
            }
          }
        }
      }
    }
  }
}
::v-deep textarea {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
::v-deep .el-select {
  width: 100%;
}
::v-deep .el-input {
  height: 32px;
}
::v-deep .el-input__inner {
  height: 32px;
}
::v-deep .el-input__icon {
  line-height: 1;
}
.el-select-dropdown__item {
  padding-left: 10px;
}
::v-deep .el-date-editor {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}
.button {
  width: 63px;
  height: 32px;
  margin-right: 5px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 3px;
}
.chaxun {
  background-color: #1890ff;
  color: #fff;
}
::v-deep .el-range-separator {
  line-height: 25px;
}
.timeTitle {
  height: 50px;
}

.dropdown-list {
  padding: 0;
  text-align: center;
  width: 50px;
}

.node-img {
  width: 16px;
  height: 16px;
  margin-right: 5px;
  vertical-align: bottom;
}
</style>
